package com.sapitest.keywords;

import com.sapitest.utils.HttpMethod;
import com.sapitest.utils.bean.Response;
import com.sapitest.utils.data.XML2JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Reporter;

import java.io.IOException;
import java.util.Optional;

/**
 * HTTP请求关键字封装类，支持post、get、head等
 * @date 2019-01-13
 * @author Liuxu
 * @version 1.0.0
 * @since jdk1.8
 */
public class HTTPClient {
    private static final Logger logger = LoggerFactory.getLogger(HTTPClient.class);

    /**
     * 关键字：发送HTTP请求
     * @param url   请求URL
     * @param method    请求方法，目前仅支持post,get,head
     * @param header    请求头字符串，格式[{"key1":"value1"},{"key2":"value2"},{"key3":"value3"}]
     * @param requestBody   请求体字符串
     * @return 自定义Response
     */
    public static Response sendHttpRequest(String url, String method, String header, String requestBody) {
        HttpMethod httpMethod = new HttpMethod();
        Response response = null;
        Reporter.log("请求地址："+ url, true);
        Reporter.log("请求方法："+ method, true);
        Reporter.log("请求头："+ header, true);
        Reporter.log("请求体："+  requestBody, true);
        try {
            if (method.equalsIgnoreCase("post")){
                response = httpMethod.post(url, header, requestBody);
            } else if (method.equalsIgnoreCase("get")){
                response =  httpMethod.get(url, header);
            } else if (method.equalsIgnoreCase("head")){
                response =  httpMethod.head(url, header);
            } else {
                logger.error("请检查输入的请求方法！");
            }
        } catch (IOException e) {
            logger.error("" + e);
        }
        printResponse(response);
        logger.info(url + "|" + method + "|" + requestBody + "|" + (response != null ? response.getResponseCode() : 0));
        return response;
    }

    /**
     * 关键字：发送HTTP请求，响应体为XML格式并转换为json格式的字符串
     * @param url   请求URL
     * @param method    请求方法，目前仅支持post,get,head
     * @param header    请求头字符串，格式[{"key1":"value1"},{"key2":"value2"},{"key3":"value3"}]
     * @param requestBody   请求体字符串
     * @return 自定义Response
     */
    public static Response sendHttpRequestXML(String url, String method, String header, String requestBody) {
        HttpMethod httpMethod = new HttpMethod();
        Response response = null;
        Reporter.log("请求地址："+ url, true);
        Reporter.log("请求方法："+ method, true);
        Reporter.log("请求头："+ header, true);
        Reporter.log("请求体："+  requestBody, true);
        try {
            if (method.equalsIgnoreCase("post")){
                response = httpMethod.post(url, header, requestBody);
                response.setResponseBody(new XML2JSON().xml2json(response.getResponseBody()));
            } else if (method.equalsIgnoreCase("get")){
                response = httpMethod.get(url, header);
                response.setResponseBody(new XML2JSON().xml2json(response.getResponseBody()));
            } else if (method.equalsIgnoreCase("head")){
                response = httpMethod.head(url, header);
                response.setResponseBody(new XML2JSON().xml2json(response.getResponseBody()));
            } else {
                logger.error("请检查输入的请求方法！");
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        printResponse(response);
        logger.info(url + "|" + method + "|" + requestBody + "|" + (response != null ? response.getResponseCode() : 0));
        return response;
    }

    private static void printResponse(Response res) {
        Optional<Response> op = Optional.ofNullable(res);
        Reporter.log("响应状态码：" + op.map(Response::getResponseCode).orElse(null), true);
        Reporter.log("响应头：" + op.map(Response::getResponseHeader).orElse(null), true);
        Reporter.log("响应体：" + op.map(Response::getResponseBody).orElse(null), true);
    }
}
